package k8s

import (
	"context"
	"fmt"
	appsv1 "k8s.io/api/apps/v1"

	"v8s-watcher/internal"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

type (
	Repository struct {
		client *kubernetes.Clientset
	}
)

func CreateRepository(client *kubernetes.Clientset) *Repository {
	return &Repository{client: client}
}

func (r *Repository) GetPods(ctx context.Context, namespace internal.Namespace) ([]corev1.Pod, error) {
	list, err := r.client.CoreV1().Pods(string(namespace)).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, fmt.Errorf("failed to get pods in namespace '%s': %w", namespace, err)
	}

	return list.Items, nil
}

func (r *Repository) GetServices(ctx context.Context, namespace internal.Namespace) ([]corev1.Service, error) {
	list, err := r.client.CoreV1().Services(string(namespace)).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, fmt.Errorf("failed to get services in namespace '%s': %w", namespace, err)
	}

	return list.Items, nil
}

func (r *Repository) GetVolumeClaims(ctx context.Context, namespace internal.Namespace) ([]corev1.PersistentVolumeClaim, error) {
	list, err := r.client.CoreV1().PersistentVolumeClaims(string(namespace)).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, fmt.Errorf("failed to get pvc in namespace '%s': %w", namespace, err)
	}

	return list.Items, nil
}

func (r *Repository) GetDeployments(ctx context.Context, namespace internal.Namespace) ([]appsv1.Deployment, error) {
	list, err := r.client.AppsV1().Deployments(string(namespace)).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, fmt.Errorf("failed to get deployment in namespace '%s': %w", namespace, err)
	}
	return list.Items, nil
}
